<!--
 * @Descripttion: 账号设置
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2021-03-11 15:42:01
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @LastEditTime: 2023-07-31 10:47:17
-->

<template>
  <div class="lb-system-news">
    <top-nav />
    <div class="page-main">
      <el-row class="page-top-operate">
        <lb-button
          type="primary"
          icon="el-icon-plus"
          @click="toShowDialog('sub')"
          v-hasPermi="`${$route.name}-add`"
          >{{ $t('menu.AccountPhoneAdd') }}</lb-button
        >
      </el-row>
      <el-table
        v-loading="loading.list"
        :data="tableData.list"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column prop="nickName" label="关联人员"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="role" label="权限内容" min-width="300">
          <template slot-scope="scope">
            <el-tag
              type="primary"
              class="mt-sm mb-sm mr-md"
              v-for="(item, index) in scope.row.node"
              :key="index"
              >{{ item | handleNodeText(authList) }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column min-width="120" label="操作">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                size="mini"
                plain
                type="primary"
                @click="toShowDialog('sub', scope.row)"
                v-hasPermi="`${$route.name}-edit`"
                >{{ $t('action.edit') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="confirmDel(scope.row.id)"
                v-hasPermi="`${$route.name}-delete`"
                >{{ $t('action.delete') }}</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :batch="false"
        :page="searchForm.list.page"
        :pageSize="searchForm.list.limit"
        :total="total.list"
        @handleSizeChange="handleSizeChange($event, 'list')"
        @handleCurrentChange="handleCurrentChange($event, 'list')"
      >
      </lb-page>

      <el-dialog
        :title="
          $t(subForm.id ? 'menu.AccountPhoneEdit' : 'menu.AccountPhoneAdd')
        "
        :visible.sync="showDialog.sub"
        width="650px"
        center
      >
        <el-form
          :model="subForm"
          ref="subForm"
          :rules="subFormRules"
          label-width="100px"
        >
          <el-form-item label="关联用户" prop="user_id">
            <el-tag
              class="cursor-pointer"
              :type="subForm.user_id ? 'primary' : 'danger'"
              @click="toShowDialog('user')"
              >{{ subForm.user_id ? subForm.nickName : '选择关联用户' }}</el-tag
            >
          </el-form-item>
          <el-form-item label="权限内容" prop="node">
            <el-checkbox-group v-model="checkList" @change="changeCheckBox">
              <div
                v-for="(item, index) in authList"
                :key="index"
                :style="{
                  display: 'inline-block',
                  marginLeft: index === 0 ? 0 : '15px'
                }"
              >
                <el-checkbox :label="item.title"></el-checkbox>
                <lb-tool-tips v-if="item.tips">{{ item.tips }}</lb-tool-tips>
              </div>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.sub = false">取 消</el-button>
          <el-button type="primary" @click="submitFormInfo" v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        title="关联用户"
        :visible.sync="showDialog.user"
        width="800px"
        center
      >
        <lb-tips v-if="routesItem.userInfo.is_admin === 0"
          >请输入用户昵称/手机号后点击查询数据</lb-tips
        >
        <el-form
          :inline="true"
          :model="searchForm.user"
          ref="userForm"
          label-width="70px"
          class="dialog-form"
        >
          <el-form-item label="输入查询" prop="phone">
            <el-input
              v-model="searchForm.user.phone"
              placeholder="请输入用户昵称/手机号"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1, 'user')"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('user')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
        <el-table
          v-loading="loading.user"
          :data="tableData.user"
          ref="singleTable"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark"
          style="width: 100%"
          highlight-current-row
          @current-change="handleSelectionChange"
        >
          <el-table-column prop="id" label="用户ID"></el-table-column>
          <el-table-column prop="avatarUrl" label="头像">
            <template slot-scope="scope">
              <lb-image :src="scope.row.avatarUrl" />
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.user.page"
          :pageSize="searchForm.user.limit"
          :total="total.user"
          @handleSizeChange="handleSizeChange($event, 'user')"
          @handleCurrentChange="handleCurrentChange($event, 'user')"
        >
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.user = false">取 消</el-button>
          <el-button
            type="primary"
            @click="handleDialogConfirm"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { mapState, mapMutations } from 'vuex'
export default {
  data () {
    return {
      checkList: [],
      authList: [{ title: '订单管理', key: 'shopOrder' }, { title: '加钟管理', key: 'shopBellOrder' }, { title: '拒单管理', key: 'shopRefuseOrder' }, { title: '服务退款', key: 'shopRefund' }, { title: '加钟退款', key: 'shopBellRefund' }],
      loading: { list: false, user: false },
      searchForm: {
        list: {
          page: 1,
          limit: 10
        },
        user: {
          page: 1,
          limit: 10,
          phone: ''
        }
      },
      tableData: { list: [], user: [] },
      total: { list: 0, user: 0 },
      showDialog: { sub: false, user: false },
      currentRow: {},
      subForm: {
        id: 0,
        user_id: '',
        nickName: '',
        node: []
      },
      subFormRules: {
        user_id: { required: true, type: 'number', message: '请选择关联用户', trigger: ['blur', 'change'] },
        node: { required: true, type: 'array', message: '请选择权限内容', trigger: ['blur', 'change'] }
      }
    }
  },
  async created () {
    this.getTableDataList(1, 'list')
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    ...mapMutations(['changeRoutesItem']),
    resetForm (form) {
      let name = `${form}Form`
      this.$refs[name].resetFields()
      this.getTableDataList(1, form)
    },
    handleSizeChange (val, key) {
      this.searchForm[key].limit = val
      this.handleCurrentChange(1, key)
    },
    handleCurrentChange (val, key) {
      this.searchForm[key].page = val
      this.getTableDataList('', key)
    },
    async getTableDataList (flag, key) {
      if (flag) this.searchForm[key].page = 1
      this.loading[key] = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm[key]))
      let methodArr = {
        list: { methodKey: 'account', methodModel: 'mobileList' },
        user: { methodKey: 'custom', methodModel: 'userSelectByPhone' }
      }
      let { methodKey, methodModel } = methodArr[key]
      let { code, data } = await this.$api[methodKey][methodModel](searchForm)
      this.loading[key] = false
      if (code !== 200) return
      this.tableData[key] = data.data
      this.total[key] = data.total
    },
    confirmDel (id) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.updateItem(id, -1, 'list')
      }).catch(() => {

      })
    },
    async updateItem (id, status, key) {
      this.$api.account.mobileStatusUpdate({ id, status }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t(status === -1 ? 'tips.successDel' : 'tips.successOper'))
          if (status === -1) {
            this.searchForm[key].page = this.searchForm[key].page < Math.ceil((this.total[key] - 1) / this.searchForm[key].limit) ? this.searchForm[key].page : Math.ceil((this.total[key] - 1) / this.searchForm[key].limit)
            this.getTableDataList('', key)
          }
        } else {
          if (status === -1) return
          this.getTableDataList('', key)
        }
      })
    },
    async toShowDialog (key, item = { id: 0, user_id: '', nickName: '', node: [] }) {
      if (key === 'sub') {
        item = JSON.parse(JSON.stringify(item))
        if (item.id) {
          let arr = []
          this.authList.map(aitem => {
            if (item.node.includes(aitem.key)) {
              arr.push(aitem.title)
            }
          })
          this.checkList = arr
        } else {
          this.checkList = []
        }
        for (let i in this.subForm) {
          this.subForm[i] = item[i]
        }
      } else {
        this.searchForm.user.phone = ''
        await this.getTableDataList(1, key)
      }
      this.showDialog[key] = !this.showDialog[key]
    },
    changeCheckBox (e) {
      let arr = []
      this.authList.map(item => {
        if (e.includes(item.title)) {
          arr.push(item.key)
        }
      })
      this.subForm.node = arr
    },
    handleSelectionChange (val) {
      val = JSON.parse(JSON.stringify(val))
      let { id, nickName } = val
      val.nickName = nickName || `用户ID ${id}`
      this.currentRow = val
    },
    handleDialogConfirm () {
      if (this.currentRow === null || !this.currentRow.id) {
        this.$message.error(`请选择用户`)
        return
      }
      let { id = 0, nickName = '' } = this.currentRow
      this.subForm.user_id = id
      this.subForm.nickName = nickName
      this.showDialog.user = false
    },
    async submitFormInfo () {
      let flag = true
      this.$refs['subForm'].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let methodModel = this.subForm.id ? 'mobileUpdate' : 'mobileAdd'
        let param = JSON.parse(JSON.stringify(this.subForm))
        delete param.nickName
        let { code } = await this.$api.account[methodModel](param)
        if (code !== 200) return
        this.$message.success(this.$t(param.id ? 'tips.successRev' : 'tips.successSub'))
        this.showDialog.sub = false
        this.getTableDataList('', 'list')
      }
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    },
    handleNodeText (val, list) {
      let arr = list.filter(item => {
        return item.key === val
      })
      return arr && arr.length > 0 ? arr[0].title : ''
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-form {
  .el-input,
  .el-select {
    width: 300px;
  }
}
</style>
